package com.binfenhulian.chinaenergy.ces.crawler.dispatcher;

import com.binfenhulian.chinaenergy.ces.crawler.core.db.dao.auto.CrawlerConfigDAO;
import com.binfenhulian.chinaenergy.ces.crawler.core.db.enums.CrawlerConfigStatusEnum;
import com.binfenhulian.chinaenergy.ces.crawler.core.db.po.auto.CrawlerConfigPO;
import com.binfenhulian.chinaenergy.ces.crawler.core.db.po.auto.CrawlerConfigPOExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 任务分发器
 * Created by wanghjbuf on 2018/3/10.
 */
@Slf4j
@Component
public class TaskDispatcher {

    @Autowired
    CrawlerConfigDAO crawlerConfigDAO;
    @Resource(name = "com.binfenhulian.chinaenergy.ces.crawler.dispatcher.TaskExecutor")
    TaskExecutor taskExecutor;

    /**
     * 执行分发
     */
    public void doDispatch() {
        log.info("----------开始执行任务分发操作-------");
        try{
            CrawlerConfigPOExample crawlerConfigPOExample = new CrawlerConfigPOExample();
            crawlerConfigPOExample.createCriteria().andStatusEqualTo(CrawlerConfigStatusEnum.RUNABLE.toString());
            List<CrawlerConfigPO> crawlerConfigPOList = crawlerConfigDAO.selectByExample(crawlerConfigPOExample);

            crawlerConfigPOList.forEach((CrawlerConfigPO crawlerConfigPO)->{
                //执行
                taskExecutor.doExecute(crawlerConfigPO);
            });
        } catch (Exception e){
          log.error("任务分发过程出现错误,操作失败!", e);
        }
        log.info("----------结束执行任务分发操作-------");
    }
}
